import {createRouter, createWebHashHistory} from 'vue-router'
import {All, Student, Teacher} from "./router";
import {getToken} from "../cookiejs/unit";
// @ts-ignore
import nprogress from 'nprogress'
import "nprogress/nprogress.css"
import store from "../store";

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        ...Student, ...All
    ]
})

router.beforeEach((to, from, next) => {
    nprogress.start()
    setTimeout(() => {
        if (to.name == 'login') {
            next()
        } else {
            let token = getToken()
            if (token) { // ? 如果有token,随意跳转页面 携带有权限的route
                store.commit('Login/admin', [...router.options.routes]) // ? 无论什么角色都添加普通路由
                if (token === 'teacher') { // ? 如果cookie是老师
                    Teacher.forEach(item => {
                        router.addRoute(item)  // ? 动态添加路由
                        store.commit('Login/vip', [item])
                    }) //! 循环权限路由并添加VUEX
                }
                next()
            } else {
                next({path: '/login'})
            }
        }
    }, 500)
})
router.afterEach(() => {
    nprogress.done()
})
export default router
